package com.mnxiaotu.common.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mnxiaotu.common.vo.Result;
import com.mnxiaotu.entity.Menu;
import com.mnxiaotu.entity.Role;
import com.mnxiaotu.entity.User;
import com.mnxiaotu.service.MenuService;
import com.mnxiaotu.service.RoleService;
import com.mnxiaotu.service.UserService;
import com.mnxiaotu.util.JwtUtils;
import com.mnxiaotu.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 登录成功处理器
 * @author java1234_小锋 （公众号：java1234）
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        //获取用户名
        String username =authentication.getName();
//        String token = JwtUtils.genJwtToken(username);

        //生成jwt
        String token = JwtUtils.genJwtToken(username);
        // 并将 token 存入 redis 中，设置过期时间是为一小时，注意：要和jwt的过期时间保持一致
        redisUtil.set(username.trim()+":","token",token,60*60);


        User currentUser = userService.getByUsername(username);

        // 根据用户id获取所有的角色信息
        List<Role> roleList = roleService.list(new QueryWrapper<Role>().inSql("id", "SELECT role_id FROM user_role WHERE user_id=" + currentUser.getId()));

        // 遍历所有的角色，获取所有菜单权限 而且不重复
        Set<Menu> menuSet=new HashSet<>();
        for(Role role:roleList){
            List<Menu> menuList = menuService.list(new QueryWrapper<Menu>().inSql("id", "SELECT menu_id FROM role_menu WHERE role_id=" + role.getId()));
            for(Menu sysMenu:menuList){
                menuSet.add(sysMenu);
            }
        }
        //将角色信息加入用户列表
        currentUser.setRoles(roleList.stream().map(Role::getRolename).collect(Collectors.joining(",")));

        List<Menu> sysmenuList=new ArrayList<>(menuSet);

        // 排序
        sysmenuList.sort(Comparator.comparing(Menu::getOrderNum));

        // 转菜单树
        List<Menu> menuList=menuService.buildTreeMenu(sysmenuList);

        outputStream.write(JSONUtil.toJsonStr(Result.ok("登录成功").put("authorization",token).put("currentUser",currentUser).put("menuList",menuList)).getBytes());
        outputStream.flush();
        outputStream.close();
    }
}
